<template>
  <el-row type="flex" class="media-board">
    <!-- 工具栏 -->
    <div class="board-layer">
      <template v-if="toolIsInit">
        <tool-box :room="this.$room" v-if="showTools" :drawable="drawable">
          <oss-upload-button
            :room="this.$room"
            :oss="netlessOssInfo"
            :appIdentifier="netlessAppid"
            :sdkToken="netlessToken"
            v-if="drawable === 'drawable'"
          >
          </oss-upload-button>
        </tool-box>
      </template>
    </div>
    <!-- 撤销/回退 -->
    <div class="redo-undo-box">
      <template v-if="roomIsInit">
        <redo-undo :room="this.$room"></redo-undo>
      </template>
    </div>
    <!-- 放大/缩小 -->
    <div class="zoom-controller-box">
      <template v-if="roomIsInit">
        <zoom-controller :room="this.$room"></zoom-controller>
      </template>
    </div>

    <!-- 分页 -->
    <div class="page-controller-box">
      <div class="page-controller-mid-box" v-if="toolIsInit">
        <el-tooltip content="文档中心" placement="top">
          <div class="page-controller-cell" v-if="roomIsInit">
            <!-- 添加白板 -->
            <preview-controller :room="this.$room"></preview-controller>
          </div>
        </el-tooltip>
        <!-- 分页 -->
        <page-controller :room="this.$room" />
      </div>
    </div>

    <!-- 举手 -->
    <div class="hands-controller-box">
      <hands-controller v-if="showControl"></hands-controller>
    </div>

    <!-- 添加一个遮罩层，防止用户可以操作音视频 -->
    <div class="disabled" v-if="!showTools"></div>

    <div ref="bindRoom" id="whiteboard" class="whiteboard" :class="drawable"></div>
  </el-row>
</template>

<script>
import Vue from 'vue'
import { videoPlugin } from '@netless/white-video-plugin'
import { audioPlugin } from '@netless/white-audio-plugin'
import { createPlugins, WhiteWebSdk, ViewMode } from 'white-web-sdk'
import OssUploadButton from './oss-upload-button/OssUploadButton'
import ToolBox from './tool-box/ToolBox'
import RedoUndo from './RedoUndo/RedoUndo'
import ZoomController from './zoom-controller/ZoomController'
import PreviewController from './preview-controller/PreviewController'
import PageController from './page-controller/PageController'
import HandsController from './hands'
import { roomStore } from '../utils/room'
import { mapState } from 'vuex'
const Identity = {
  creator: 'creator',
  joiner: 'joiner'
}
export default {
  name: 'Whiteboard',
  components: {
    OssUploadButton,
    ToolBox,
    RedoUndo,
    ZoomController,
    PreviewController,
    PageController,
    HandsController
  },
  data() {
    return {
      identity: Identity.creator,
      roomStore: roomStore,
      roomIsInit: false,
      toolIsInit: false
    }
  },
  computed: {
    ...mapState('live', ['netlessAppid', 'netlessToken', 'netlessOssInfo']),
    me() {
      return this.roomStore.state.me
    },
    showControl() {
      if (+this.roomStore.state.me.role === 1) return true
      if (this.$route.path.match(/big-class/)) {
        if (+this.roomStore.state.me.role === 2) {
          return true
        }
      }
      return false
    },
    screenId() {
      const course = this.roomStore.state.course
      let teacher = {}
      this.roomStore.state.users.forEach(item => {
        if (item.uid == course.teacherId) {
          teacher = item
        }
      })
      let id = ''
      if (teacher) {
        id = teacher.screenId
      }
      return id
    },
    sharedStream() {
      if (this.roomStore.state.rtc.localSharedStream) {
        const _tmpStream = {
          ...this.roomStore.state.rtc.localSharedStream,
          video: 1,
          audio: 1,
          local: true
        }
        return _tmpStream
      }
      let remoteStream = {}
      this.roomStore.state.rtc.remoteStreams.forEach(item => {
        if (item.uid == `${this.screenId}`) {
          remoteStream = item
        }
      })
      if (!this.$util.isEmpty(remoteStream)) {
        const _tmpStream = {
          ...remoteStream,
          video: 1,
          audio: 1
        }
        return _tmpStream
      }
      return null
    },
    drawable() {
      if (this.$route.path.match('small-class|big-class')) {
        if (+this.me.role === 1) {
          return 'drawable'
        }
        if (+this.me.role === 2) {
          if (this.me.grantBoard) {
            return 'drawablePanel'
          } else {
            return 'panel'
          }
        }
      }
      return 'drawable'
    },
    showTools() {
      return this.drawable !== 'panel'
    }
  },
  methods: {
    async startJoinRoom() {
      try {
        const uuid = this.roomStore.state.course.boardId
        const userId = this.roomStore.state.me.uid
        const roomToken = this.roomStore.state.course.boardToken
        const plugins = createPlugins({
          video: videoPlugin,
          audio: audioPlugin
        })
        plugins.setPluginContext('video', {
          identity: this.identity === Identity.creator ? 'host' : ''
        })
        plugins.setPluginContext('audio', {
          identity: this.identity === Identity.creator ? 'host' : ''
        })
        const whiteWebSdk = new WhiteWebSdk({
          appIdentifier: this.netlessAppid,
          plugins: plugins
        })
        const room = await whiteWebSdk.joinRoom(
          {
            uuid: uuid,
            roomToken: roomToken,
            isRecord: true,
            userPayload: {
              userId: userId
            },
            floatBar: true
          },
          {
            onPhaseChanged: phase => {
              this.phase = phase
              console.log(`room ${uuid} change: ${phase}`)
            },
            onDisconnectWithError: error => {
              console.error(error)
            },
            onKickedWithReason: reason => {
              console.error('kicked with reason: ' + reason)
            }
          }
        )
        room.setMemberState({
          pencilOptions: {
            disableBezier: false,
            sparseHump: 1.0,
            sparseWidth: 1.0,
            enableDrawPoint: false
          }
        })
        room.bindHtmlElement(this.$refs.bindRoom)
        if (this.roomStore.state.me.role == 1) {
          this.roomIsInit = true
        }
        Vue.prototype.$room = room
        if (this.roomStore.state.me.role == 1) {
          if (this.roomStore.state.course.lockBoard) {
            room.setViewMode(ViewMode.Broadcaster)
          } else {
            room.setViewMode(ViewMode.Freedom)
          }
        }
        if (this.roomStore.state.me.role === 2) {
          if (this.roomStore.state.course.lockBoard) {
            room.handToolActive = false
            room.disableCameraTransform = true
            room.setViewMode(ViewMode.Follower)
          } else {
            room.disableCameraTransform = false
            room.setViewMode(ViewMode.Freedom)
          }
          if (!this.roomStore.state.me.grantBoard) {
            room.disableDeviceInputs = true
          } else {
            room.disableDeviceInputs = false
          }
        }
        this.toolIsInit = true
      } catch (error) {
        console.error(error)
      }
    },
    // 退出教室
    async handleGoBack() {
      await this.$room.disconnect()
    }
  },
  async mounted() {
    await this.startJoinRoom()
  },
  created() {
    Vue.prototype.$room = undefined
  },
  watch: {
    'roomStore.state.course.lockBoard': {
      handler(n, o) {
        if (n != o) {
          if (this.roomStore.state.me.role === 2) {
            if (n) {
              this.$room.disableCameraTransform = true
            } else {
              this.$room.disableCameraTransform = false
            }
          }
        }
      }
    },
    'roomStore.state.me.grantBoard': {
      handler(n, o) {
        if (n != o) {
          if (this.roomStore.state.me.role === 2) {
            if (!n) {
              this.$room.disableDeviceInputs = true
            } else {
              this.$room.disableDeviceInputs = false
            }
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.media-board {
  flex: 1 0;
  overflow: hidden;
  background-color: #fff;
  position: relative;
  .whiteboard {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }
  .whiteboard.panel {
    // pointer-events: none;
    ::v-deep .netless-whiteboard.cursor-pencil {
      cursor: pointer !important;
    }
  }
  .board-layer {
    height: 100%;
    width: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: absolute;
    z-index: 10;
    left: 24px;
  }
  .redo-undo-box {
    position: absolute;
    z-index: 10;
    bottom: 30px;
    left: 24px;
  }
  .zoom-controller-box {
    position: absolute;
    left: 120px;
    z-index: 10;
    bottom: 30px;
  }
  .page-controller-box {
    position: absolute;
    z-index: 10;
    bottom: 30px;
    right: 24px;
    .page-controller-mid-box {
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: white;
      height: 40px;
      padding-left: 4px;
      padding-right: 4px;
      border-radius: 4px;
      user-select: none;
      font-size: 12px;
      box-shadow: 0 8px 24px 0 rgba(0, 0, 0, 0.08);
    }
    .page-controller-cell {
      width: 32px;
      height: 32px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      background-color: white;
      border-radius: 2px;

      &:hover {
        background: rgba(33, 35, 36, 0.1);
      }
    }
  }
  .hands-controller-box {
    position: absolute;
    right: 24px;
    z-index: 10;
    bottom: 88px;
  }
}
.disabled {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 9;
}
</style>
